package com.base.service.impl;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.vo.PageRequestHelperVo;
import com.base.vo.RepositorySource;
import com.base.service.RepositorySourceService;
import com.base.mapper.RepositorySourceMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 *
 */
@Service
public class RepositorySourceServiceImpl extends ServiceImpl<RepositorySourceMapper, RepositorySource>
implements RepositorySourceService{

    @Autowired
    DataSource dataSource;

    @Autowired
    DataSourceCreator dataSourceCreator;

    @Override
    public IPage page(PageRequestHelperVo pageRequestHelperVo) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like(StringUtils.isNotBlank(pageRequestHelperVo.getKeyword()),"name",pageRequestHelperVo.getKeyword());
        wrapper.eq(StringUtils.isNotBlank(pageRequestHelperVo.getType()),"repository_id",pageRequestHelperVo.getType());
        IPage<RepositorySource> page = new Page<>(pageRequestHelperVo.getPageNum(), pageRequestHelperVo.getPageSize());
        return page(page,wrapper);
    }

    /**
     * 校验连接
     *
     * @param repositorySource
     * @return
     */
    @Override
    public boolean testConnection(RepositorySource repositorySource) {
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        BeanUtils.copyProperties(repositorySource,dataSourceProperty);
        DataSource ds = dataSourceCreator.createDataSource(dataSourceProperty);
        if(ds!=null){
            try {
                ds.getConnection().close();
                return true;
            } catch (SQLException throwables) {
                return false;
            }
        }
        return false;
    }
}




